/*jshint esversion: 6 */

var url = require('url')
		,routes = require('./route.js')
		,responses = require('./response.js')
		,requestObj = require('./request.js')
		,globals = require('./globals.js');

module.exports = {
	RouteRequest: function(request, response, routetable){
		let found = false, urlPath = url.parse(request.url).path;
		for(let routes in routetable)
		{
			let element = routetable[routes];
			let regTest = element.regExp.test(urlPath);
			console.log(element.regExp);
			if(element.hasOwnProperty('regExp') && element.regExp !== null && element.regExp !== undefined
			&& regTest && element.formMethod === request.method){
				found = true;
				let path = globals.settings.controller + '/' + element.controller + '.js';
				let controller = require(path);

				if(typeof controller[element.actionMethod] === 'function'){
					try{
						requestObj.negotiate(request);
						//Content type not acceptable
						console.log('Formatter Returned : ' + request.formatters);
						if(request.formatters === '')
							return responses["406"](request, response);
						requestObj.fillParams(request, element.regExpForParams);
						controller[element.actionMethod](request, response);
						return responses["200"](request, response);
					}catch(err){
						return responses["500"](request, response);
					}
				}
				if(found){
					break;
				}
			};
		}
		if(!found){
			return responses["404"](request, response);
		}
	}
};
